﻿Imports System.Management
Imports System.Net
Imports Sunts.HyperV.ServiceControl
Imports Sunts.HyperV.Common
Imports System.IO

Imports System.Security.Principal
Imports System.Runtime.InteropServices

Public Class frmInstallRemoteService


    Private Sub InstallRemoteService_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Try
            cmbHostName.Items.Clear()
            cmbHostName.DataSource = HyperVHost.SelectAllRemote(My.Settings.ConnectionString)
            cmbHostName.DisplayMember = "HostName"
            cmbHostName.ValueMember = "HostID"
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub

    Private Sub btnDeploy_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDeploy.Click
        Dim Uri As Uri
        Dim ConnectionOptions As ConnectionOptions
        Dim InstallService As ServiceControl.ReturnValue


        Try
            For Each ctrl As Control In Me.Controls
                If ctrl.Name.StartsWith("txt") Or ctrl.Name.StartsWith("cmb") Then
                    If ctrl.Text = String.Empty Then
                        MessageBox.Show("Please enter information for " & Mid(ctrl.Name, 4))
                        Exit Sub
                    End If
                End If
            Next

            Using UNCAccessWithCredentials As New UNCAccessWithCredentials()
                If UNCAccessWithCredentials.NetUseWithCredentials("\\192.168.16.67\c$", Me.txtHostUsername.Text, "", Me.txtHostPassword.Text) Then
                    For Each File As String In Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory)
                        Uri = New Uri(String.Format("file://{0}/c$/Program Files/Poached Productions/Hyper-V Backup/{1}", Me.cmbHostName.Text, Path.GetFileName(File)))
                        IO.Directory.CreateDirectory(Path.GetDirectoryName(Uri.LocalPath))
                        My.Computer.Network.UploadFile(File, Uri, Nothing, False, 2000)
                    Next
                Else
                    MessageBox.Show("Failed to connect to " & vbCrLf & "LastError = " & UNCAccessWithCredentials.LastError.ToString(), "Failed to connect", MessageBoxButtons.OK, MessageBoxIcon.[Error])
                End If
            End Using
        Catch ex As Exception
            MessageBox.Show("Could not deploy the remote service due to the following error" & vbCrLf & ex.Message)
            Exit Sub
        End Try

        Dim HostName = Me.cmbHostName.Text

        Try
            ConnectionOptions = New ConnectionOptions
            ConnectionOptions.Username = Me.txtHostUsername.Text
            ConnectionOptions.Password = Me.txtHostPassword.Text

            Dim ms As New ManagementScope("\\" & HostName & "\root\cimv2", ConnectionOptions)
            ms.Connect()

            If ServiceControl.IsServiceInstalled(HostName, ConnectionOptions) = True Then
                MessageBox.Show("The service is already installed on this host")
                Exit Sub
            End If

            InstallService = ServiceControl.InstallService(HostName, ConnectionOptions)
            Select Case InstallService
                Case ServiceControl.ReturnValue.Success
                    MessageBox.Show("Service deployed successfully.")
                Case ServiceControl.ReturnValue.NotSupported
                    MessageBox.Show("This deployment is not supported.")
                Case ServiceControl.ReturnValue.AccessDenied
                    MessageBox.Show("The service was not deployed as there was an access is denied error.")
                Case ServiceControl.ReturnValue.StatusServiceExists
                    MessageBox.Show("The service already exists.")
                Case Else
                    MessageBox.Show("The service could not be deployed due to an undetermined error (Error " & InstallService & ")")
            End Select

        Catch ex As Exception
            If ex.Message.Contains("0x80070005") Then
                MsgBox("Could not connect to the server, please check the credentials", vbCritical, "Connection error")
            Else
                MsgBox(ex.Message, vbCritical, "Connection error")
            End If
            Exit Sub
        End Try

    End Sub

    Private Sub cmbHostName_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmbHostName.SelectedIndexChanged
        Dim HyperVHost As HyperVHost

        Try
            HyperVHost = CType(cmbHostName.SelectedItem, HyperVHost)
            Me.txtHostUsername.Text = HyperVHost.Username
            Me.txtHostPassword.Text = HyperVHost.Password
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub

    Private Sub chkShowPassword_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chkShowPassword.CheckedChanged
        If Me.chkShowPassword.Checked = True Then
            Me.txtHostPassword.PasswordChar = Nothing
        Else
            Me.txtHostPassword.PasswordChar = CChar("*")
        End If
    End Sub
End Class







